/**
 * Copyright (c) 2010-2011 Pierre Labatut
 *
 * This file is part of Space-Chronicles project.
 *
 * Space-Chronicles is free software: you can redistribute it and/or modify it
 * under the terms of its license which may be found in the accompanying
 * LICENSE file or <http://code.google.com/p/space-chronicles/>.
 */
package space.app.meshview;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.filechooser.FileFilter;

import space.app.common.Application;
import space.app.common.ServerFrame;
import space.game.ShaderProgram;

/**
 *
 * @author Pierre
 */
public class MeshFrame extends ServerFrame<MeshMessage> {

    final MeshRendrer renderer;
    ShaderProgram currentShader;

    @Override
    public void onServerRecieved(MeshMessage message) {
        renderer.load(message.url);
    }

    @Override
    protected List<Image> createImages() {
        return loadImages("mesh-viewer-icon-16.png",
                "mesh-viewer-icon-24.png",
                "mesh-viewer-icon-32.png");
    }

    /** Creates new form MeshViewFrame */
    public MeshFrame(final Application<MeshMessage> application, final URL file) throws MalformedURLException {
        super(application);

        if (application == null) {
            throw new NullPointerException();
        }
        initComponents();

        {
            final String preferedShaderName = application.preferenceNode().get("shader",
                    ShaderProgram.values()[0].name());

            try {
                currentShader = ShaderProgram.valueOf(preferedShaderName);
            } catch (IllegalArgumentException e) {
                currentShader = ShaderProgram.values()[0];
            }

            final ButtonGroup group = new ButtonGroup();
            for (final ShaderProgram sp : ShaderProgram.values()) {
                final JRadioButtonMenuItem item = new javax.swing.JRadioButtonMenuItem();
                item.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        currentShader = sp;
                        MeshFrame.this.renderer.useShader(sp);
                    }
                });
                item.setSelected(sp == currentShader);
                item.setText(sp.name);
                group.add(item);
                jViewMenu.add(item);
            }
        }

        renderer = new MeshRendrer(jJOGLPanel1, currentShader);
        renderer.initialize();
        // file is specified When a
        if (file != null) {
            renderer.load(file);
        }

        {
            final Preferences node = application.preferenceNode();
            final boolean showTBN = node.getBoolean("showTBN", false);
            jShowTBNItem.setSelected(showTBN);
            renderer.setTBNVisible(showTBN);
            final boolean showFBO = node.getBoolean("showFBO", false);
            jShowFBOItem.setSelected(showFBO);
            renderer.setFBOVisible(showFBO);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jStatusPanel = new javax.swing.JPanel();
        jStatusLabel = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jJOGLPanel1 = new space.app.common.JOGLPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jFileMenu = new javax.swing.JMenu();
        jOpenMenuItem = new javax.swing.JMenuItem();
        jExitMenuItem = new javax.swing.JMenuItem();
        jViewMenu = new javax.swing.JMenu();
        jAllwaysOnTopMenuItem = new javax.swing.JCheckBoxMenuItem();
        jSeparator4 = new javax.swing.JPopupMenu.Separator();
        jShowTBNItem = new javax.swing.JCheckBoxMenuItem();
        jShowFBOItem = new javax.swing.JCheckBoxMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        jServerMenu = new javax.swing.JMenu();
        jStartMenuItem = new javax.swing.JMenuItem();
        jStopMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jPrefMenu = new javax.swing.JMenuItem();
        jHelpMenu = new javax.swing.JMenu();
        jHelpMenuItem = new javax.swing.JMenuItem();
        jActionMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Mesh Viewer");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jStatusPanel.setLayout(new java.awt.BorderLayout());

        jStatusLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/space/app/common/network-offline-16.png"))); // NOI18N
        jStatusLabel.setText("Press F5 to start the server.");
        jStatusPanel.add(jStatusLabel, java.awt.BorderLayout.CENTER);
        jStatusPanel.add(jSeparator2, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(jStatusPanel, java.awt.BorderLayout.SOUTH);
        getContentPane().add(jJOGLPanel1, java.awt.BorderLayout.CENTER);

        jFileMenu.setText("File");

        jOpenMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jOpenMenuItem.setText("Open");
        jOpenMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jOpenMenuItemActionPerformed(evt);
            }
        });
        jFileMenu.add(jOpenMenuItem);

        jExitMenuItem.setAction(exitAction);
        jExitMenuItem.setText("Exit");
        jFileMenu.add(jExitMenuItem);

        jMenuBar1.add(jFileMenu);

        jViewMenu.setText("View");
        jViewMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jViewMenuActionPerformed(evt);
            }
        });

        jAllwaysOnTopMenuItem.setAction(allwaysOnTopAction);
        jAllwaysOnTopMenuItem.setText("Always on Top");
        jViewMenu.add(jAllwaysOnTopMenuItem);
        jViewMenu.add(jSeparator4);

        jShowTBNItem.setSelected(true);
        jShowTBNItem.setText("Show Tangent Space");
        jShowTBNItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jShowTBNItemActionPerformed(evt);
            }
        });
        jViewMenu.add(jShowTBNItem);

        jShowFBOItem.setSelected(true);
        jShowFBOItem.setText("Show Shadow Map");
        jShowFBOItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jShowFBOItemActionPerformed(evt);
            }
        });
        jViewMenu.add(jShowFBOItem);
        jViewMenu.add(jSeparator3);

        jMenuBar1.add(jViewMenu);

        jServerMenu.setText("Server");

        jStartMenuItem.setAction(startServerAction);
        jStartMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        jStartMenuItem.setText("Start");
        jServerMenu.add(jStartMenuItem);

        jStopMenuItem.setAction(stopServerAction);
        jStopMenuItem.setText("Stop");
        jStopMenuItem.setEnabled(false);
        jServerMenu.add(jStopMenuItem);
        jServerMenu.add(jSeparator1);

        jPrefMenu.setAction(showPreferencesAction);
        jPrefMenu.setText("Preferences...");
        jServerMenu.add(jPrefMenu);

        jMenuBar1.add(jServerMenu);

        jHelpMenu.setText("Help");

        jHelpMenuItem.setAction(showHelpAction);
        jHelpMenuItem.setText("Help");
        jHelpMenu.add(jHelpMenuItem);

        jActionMenuItem.setAction(showAboutAction);
        jActionMenuItem.setText("About");
        jHelpMenu.add(jActionMenuItem);

        jMenuBar1.add(jHelpMenu);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jOpenMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jOpenMenuItemActionPerformed
        final Preferences node = application.preferenceNode();
        final JFileChooser fc = new JFileChooser(node.get("lastDirectory", null));

        fc.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(final File f) {
                return f.getName().endsWith(".mesh") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "Mesh Definition (.mesh)";
            }
        });
        
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                final URL url = fc.getSelectedFile().toURI().toURL();
                getStatusLablel().setText("Load " + url);
                renderer.load(url);
            } catch (MalformedURLException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            node.put("lastDirectory", fc.getCurrentDirectory().getCanonicalPath());
            node.flush();
        } catch (BackingStoreException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jOpenMenuItemActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            final Preferences node = application.preferenceNode();
            node.putBoolean("alwaysOnTop", jAllwaysOnTopMenuItem.isSelected());
            node.putBoolean("showTBN", jShowTBNItem.isSelected());
            node.putBoolean("showFBO", jShowFBOItem.isSelected());
            node.put("shader", currentShader.name());
            node.flush();
        } catch (BackingStoreException ex) {
            Logger.getLogger(MeshFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowClosing

    private void jViewMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jViewMenuActionPerformed
    }//GEN-LAST:event_jViewMenuActionPerformed

    private void jShowTBNItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jShowTBNItemActionPerformed
        renderer.setTBNVisible(jShowTBNItem.isSelected());
    }//GEN-LAST:event_jShowTBNItemActionPerformed

    private void jShowFBOItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jShowFBOItemActionPerformed
        renderer.setFBOVisible(jShowFBOItem.isSelected());
    }//GEN-LAST:event_jShowFBOItemActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem jActionMenuItem;
    private javax.swing.JCheckBoxMenuItem jAllwaysOnTopMenuItem;
    private javax.swing.JMenuItem jExitMenuItem;
    private javax.swing.JMenu jFileMenu;
    private javax.swing.JMenu jHelpMenu;
    private javax.swing.JMenuItem jHelpMenuItem;
    private space.app.common.JOGLPanel jJOGLPanel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jOpenMenuItem;
    private javax.swing.JMenuItem jPrefMenu;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JPopupMenu.Separator jSeparator4;
    private javax.swing.JMenu jServerMenu;
    private javax.swing.JCheckBoxMenuItem jShowFBOItem;
    private javax.swing.JCheckBoxMenuItem jShowTBNItem;
    private javax.swing.JMenuItem jStartMenuItem;
    private javax.swing.JLabel jStatusLabel;
    private javax.swing.JPanel jStatusPanel;
    private javax.swing.JMenuItem jStopMenuItem;
    private javax.swing.JMenu jViewMenu;
    // End of variables declaration//GEN-END:variables

    @Override
    protected JLabel getStatusLablel() {
        return jStatusLabel;
    }
}
